<template>
  <!-- 价格策略管理 -->
  <div class="container">
    <section class="left-container">
      <el-tree
        :data="data"
        :props="defaultProps"
        :expand-on-click-node="false"
        class="tree-wrapper"
        @node-click="getList2($event,page,null,orderBy.name, orderBy.method);"
      >
      </el-tree>
    </section>

    <section class="right-container">
    <div style="margin-top: 20px">
      <el-button type="primary" size="small" style="margin-right:5px"  @click="add" v-if="hasPermission('company:company:add')">新增</el-button>
      <section class="right-but" style="display:flex;margin-bottom:0px">
      <el-button style="margin-right:-13px;cursor:pointer;"  @click="getList(page,orderBy.name,orderBy.method,queryForm.name,queryForm.checkedState)">
        <img style="width:44px;height:36px;" src="~@/assets/img/shuaxin.png" >
      </el-button>
        <PopoverBut :checkedProps="checkedProps" :options="options" @getCheckeds="handlerCloumn"></PopoverBut>
      </section>
    </div>
      <el-table
        size="mini"
        v-loading="loading"
        :data="tableData"
        style="width: 100%; margin-top: 10px"
        border
        :header-cell-style="{
          'background-color': '#eeeeee !important',
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="序号" width="70" align="center">
          <template slot-scope="scope">
            <span>{{
              (page.pageNo - 1) * page.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" min-width="110px"> </el-table-column>
        <el-table-column prop="effectTime" min-width="200px" label="开始时间">
        </el-table-column>
        <el-table-column prop="endTime" min-width="200px" label="结束时间"></el-table-column>
        <el-table-column prop="priceLower,priceUpper" label="价格" min-width="140px" align="right">
          <template slot-scope="scope">
            {{scope.row.priceLower | thousandSep}}～{{scope.row.priceUpper  | thousandSep}}
          </template>
        </el-table-column>
        <span v-for="(item, index) in checkedProps" :key="index">
          <el-table-column  prop="createDate" min-width="200px" :label="item" v-if="item==='创建时间'"></el-table-column>
          <el-table-column  prop="createBy.loginName" min-width="110" :label="item" v-if="item==='创建人'"></el-table-column>
          <el-table-column  prop="updateDate" min-width="200px" :label="item" v-if="item==='上次操作时间'"></el-table-column>
          <el-table-column  prop="updateBy.loginName" min-width="120" :label="item" v-if="item==='上次操作人'"></el-table-column>
        </span>
        <el-table-column prop="state" label="状态" width="110">
          <template slot-scope="scope">
            <section class="activate-state" v-if="scope.row.state===1">
              <i></i>
              {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
            </section>
            <section class="inactive-state" v-else>
              <i></i>
              {{$dictUtils.getDictLabel("state", scope.row.state, "")}}
            </section>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="252">
          <template slot-scope="scope">
            <template v-for="item in $dictUtils.getDictList('state')">
              <el-link type="primary" v-if="item.value !=='-1'&& item.value!==(scope.row.state+'')&&item.label!=='未启用'&&(!(scope.row.state===-1&& item.value==='0')||item.value==scope.row.state)" :underline="false" @click="isRepeat(item.value,scope.row)"  :disabled="(scope.row.state===-1&& item.value==='0')||item.value==scope.row.state"
              >{{item.label}}
              </el-link>
<!--              <span v-if="scope.row.state === -1 || scope.row.state === 0" class="operation">-->
<!--                <el-link type="primary"  v-if="item.value ==='1'"-->
<!--                         :underline="false" @click="editState(item.value,scope.row)">{{item.label}}-->
<!--              </el-link>-->
<!--              </span>-->
<!--              <span v-if="scope.row.state === 1"  class="operation">-->
<!--                <el-link type="primary"  v-if="item.value ==='0'"-->
<!--                         :underline="false" @click="editState(item.value,scope.row)">{{item.label}}-->
<!--              </el-link>-->
<!--              </span>-->
            </template>

            <el-link type="primary" :underline="false" v-if="hasPermission('product:price:edit')" @click="edit(scope.row)">修改
            </el-link>
            <el-link type="primary" :underline="false" v-if="hasPermission('product:price:delete')&&scope.row.state === -1" @click="delPrice(scope.row.id,scope.row.state)">删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="page.pageSize"
        :current-page="page.pageNo"
        layout="total,sizes,prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
      <EditForm
        ref="EditForm"
        @refreshDataList="getList(page,orderBy.name,orderBy.method)"
      ></EditForm>
    </section>
  </div>
</template>
<script>
import { getList, delPrice, editState, getById, isRepeat} from '@/api/market/productPrice.js'
import { getTreeData } from '@/api/market/product.js'
import EditForm from './editForm'
import PopoverBut from '@/components/button/popoverBut'
const options1 = []
const cityOptions = ['上海', '北京']
export default {
  components: {
    EditForm,
    PopoverBut
  },

  data () {
    return {
      msg: '',
      data: [],
      repeatIds: [],
      categoryData: {},
      defaultProps: {
        // 修改el-tree默认data数组参数
        label: 'name',
        id: 'id',
        parentId: 'parentId',
        children: 'children'
      },
      checkedProps: options1,
      ShowCloum: { createDate: '' },
      options: [
        { label: '创建人', key: 'createBy.loginName' },
        { label: '创建时间', key: 'createDate' },
        { label: '上次操作人', key: 'updateBy.loginName' },
        { label: '上次操作时间', key: 'updateDate' }
      ],
      tableData: [],
      orderBy: {
        name: 'update_date',
        method: 'desc'
      },
      loading: false,
      page: {
        pageSize: 10,
        pageNo: 1,
        total: 0
      },
      props: 1,
      queryForm: {
        checkedCities: 0
      },
      checkedCities: [],
      cities: cityOptions
    }
  },
  methods: {
    // 获取列表带分页
    getList ( params, orderName, orderByAORC, queryNames, queryState) {
      this.loading = true
        console.log(this.categoryData.id)
      getList({
        pageSize: params.pageSize,
        pageNo: params.pageNo,
        orderBy: orderName,
        orderByAORC: orderByAORC,
          productCategoryId: this.categoryData.id,
        names: queryNames,
        state: queryState
      }).then((res) => {
        if (res.data.code === '200') {
          this.tableData = res.data.result.list
          this.page.total = res.data.result.count
        }
        this.loading = false
      })
    },
    // 获取产品目录
    getTreeData (id) {
      getTreeData({ id: id }).then((res) => {
        if (res.data.code === '200') {
          this.data = res.data.result
        }
      })
    },
    getList2 ($event, params, props, orderName, orderByAORC, queryNames, queryState) {
      console.log($event)
      params.pageNo = 1
      this.categoryData = $event
      this.loading = true
      getList({
        pageSize: params.pageSize,
        pageNo: params.pageNo,
        productCategoryId: $event.id,
        props: props,
        orderBy: orderName,
        orderByAORC: orderByAORC,
        names: queryNames,
        state: queryState
      }).then((res) => {
        if (res.data.code === '200') {
          this.tableData = res.data.result.list
          this.page.total = res.data.result.count
        }
        this.loading = false
      })
    },
    // 删除价格策略
    delPrice (ids, state) {
      if (state === 1) {
        this.$notify.error({
          title: '错误',
          message: '已启用，不支持删除！如果不继续使用，可将此策略停用！'
        });
      } else if (state === 0) {
        this.$notify.error({
          title: '错误',
          message: '已停用，不允许任何操作！'
        });
      } else if (state === -1) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((res) => {
          delPrice ({
            ids: ids
          }).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '已删除!'
              })
              this.getList(this.page,this.orderBy.name,this.orderBy.method)
            }
          })
        });
      }

    },
    // 添加
    add () {
      this.$refs.EditForm.init('add')
    },
    // 编辑
    edit (row) {
      getById({id: row.id}).then((res) => {
        if (res.data.code === '200') {
          let editForm = {}
          editForm.productId = res.data.result.productId
          editForm.productName = res.data.result.productName
          editForm.id = res.data.result.id
          editForm.priceUpper = res.data.result.priceUpper
          editForm.priceLower = res.data.result.priceLower
          editForm.effectTime = res.data.result.effectTime
          editForm.endTime = res.data.result.endTime
          this.$refs.EditForm.init('edit', editForm)
        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
      })
    },
    // 检测时间重复
    isRepeat (event, row) {
      var msg;
      if (row.state === 0 || row.state === -1) {
        isRepeat({
          id: row.id
        }).then((res) => {
          if (res.data.code === '200') {
            console.log(res.data.result)
            if (res.data.result.length > 0) {
              this.repeatIds = res.data.result;
              this.msg = row.productName + '的此条价格策略与历史价格策略有冲突，启用后以前的价格策略则自动停用，确定启用吗？';
              console.log(this.msg)
              console.log(event)
              console.log(row.id)

              this.editState(event, row.id)
            } else {
              this.msg = '您是否要' + this.$dictUtils.getDictLabel("state", event, "") + '?'
              this.repeatIds = []
              this.editState(event, row.id)
            }
          }
        });
      } else if (row.state === 1) {
        this.msg = '停用后，该价格策略将不在有效，确认停用吗？';
        this.repeatIds = []
        this.editState(event, row.id)

      }
    },
    // 修改状态
    editState (state, id) {
      this.$confirm(this.msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        editState({ id: id, state: state, repeatIds: this.repeatIds }).then((res) => {
          if (res.data.code === '200') {
            this.getList(this.page,this.orderBy.name,this.orderBy.method)
            if (state === '1') {
              console.log(state)
              this.$message({
                type: 'success',
                message: '已启用'
              });
            }else if (state === '0') {
              this.$message({
                type: 'success',
                message: '已停用'
              });
            }
          } else {
            this.$message({
              type: 'warning',
              message: res.data.message
            })
          }
        })
      });
    },
    // 是否显示某列数据
    handlerCloumn (e) {
      this.checkedProps = e
      // console.log(e)
    },
    // 重置查询条件
    reset () {
      this.queryForm = {}
        this.getList(this.page,this.orderBy.name,this.orderBy.method)
    },
    handleSizeChange (e) {
      this.page.pageSize = e
      this.getList(this.page,this.orderBy.name,this.orderBy.method)
    },
    handleCurrentChange (e) {
      this.page.pageNo = e
      this.getList(this.page,this.orderBy.name,this.orderBy.method)
      console.log(e)
    },
    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      } else {
        return 'success-row'
      }
    }
  },
  mounted () {
    // this.tableData = [{ names: '1' }]
    this.getList(this.page,this.orderBy.name,this.orderBy.method)
    this.getTreeData(0)
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-input--small .el-input__inner {
  height: 36px;
  line-height: 32px;
  width: 230px;
}
.container {
  display: flex;
  width: 100%;
  background-color: #F7F7F7;
  height: calc(100vh - 124px);
}
.left-container {
  width: 250px;
  background-color: #ffffff;
  border-radius: 6px;
  overflow:auto;
  ::v-deep.el-tree{
    .custom-tree-node{
      font-size: 16px;
    }
  }
}
.right-container {
  margin-left: 10px;
  width: 100%;
  padding-left: 10px;
  border-radius: 6px;
  background-color: #ffffff;
  overflow-y: auto;
  padding-bottom: 20px;

  .el-popover__reference{
    img{
      position: relative;
    }
  }
}
.queryForm {
  position: relative;
  .but-container {
    top: 10px;
    margin-left: 20px;
  }
}
.right-but {
  float: right;
  ::v-deep .el-button{
    border: 1px solid transparent !important;
  }
}
.el-table .success-row {
  background: #f0f9eb;
}
::v-deep .el-table .warning-row {
  background: #f7f7f7;
}
</style>
